<template>
  <div class="user-layout-wrapper">
    <div class="container">
      <div class="user-layout-content">
        <div class="top">
          <div class="header">
            <a href="/">
              <!--              <img src="~@/assets/logo.pic.jpg" class="logo" alt="logo" />-->
              <span class="title">城艺通广告管理系统</span>
            </a>
          </div>
          <div class="desc"></div>
        </div>

        <div class="main">
          <a-form
            ref="formLogin"
            :rules="rules"
            class="user-layout-login"
            :model="formState"
            @finish="onFinish"
            @finish-failed="onFinishFailed"
          >
            <a-form-item name="email">
              <a-input v-model:value="formState.email" size="large" type="text" placeholder="邮箱">
                <template #prefix>
                  <user-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                  <!-- <a-icon type="user" :style="{ color: 'rgba(0,0,0,.25)' }" /> -->
                </template>
              </a-input>
            </a-form-item>

            <a-row :gutter="16">
              <a-col class="gutter-row" :span="16">
                <a-form-item name="captcha">
                  <a-input v-model:value="formState.captcha" size="large" type="text" placeholder="验证码">
                    <template #prefix>
                      <mail-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                      <!-- <a-icon type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" /> -->
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="8">
                <a-button
                  class="getCaptcha"
                  tabindex="-1"
                  :disabled="state.captchaBtnDisabled"
                  @click.stop.prevent="getCaptcha"
                >
                  {{ (!state.captchaBtnDisabled && '获取验证码') || state.time + ' s' }}
                </a-button>
              </a-col>
            </a-row>

            <!-- <a-form-item name="remember">
              <a-checkbox v-model:checked="formState.remember">自动登录</a-checkbox>
            </a-form-item> -->

            <a-form-item style="margin-top: 24px">
              <a-button
                size="large"
                type="primary"
                html-type="submit"
                class="login-button"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
              >
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </div>

        <!-- <div class="footer">
          <div class="links">
            <a href="_self">帮助</a>
            <a href="_self">隐私</a>
            <a href="_self">条款</a>
          </div>
          <div class="copyright">Copyright &copy; 2018 vueComponent</div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// import md5 from 'md5';
import { notification } from 'ant-design-vue';
import { UserOutlined, MailOutlined } from '@ant-design/icons-vue';
import type { FormInstance } from 'ant-design-vue/es';
import type { Rule } from 'ant-design-vue/es/form';
import { getEmailCaptcha, login } from '@/api/login';
import { useUserStore } from '@/store';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const formLogin = ref<FormInstance>();
const isLoginError = ref(false);
const rules: Record<string, Rule[]> = {
  email: [
    {
      required: true,
      // TODO: 应该如何校验呢？
      // pattern:
      //   /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入邮箱！',
      trigger: 'change',
    },
  ],
  captcha: [{ required: true, message: '请输入验证码！', trigger: 'blur' }],
};
const formState = reactive({
  email: '',
  captcha: '',
  remember: true,
});
const state = reactive({
  time: 60,
  loginBtn: false,
  captchaBtnDisabled: false,
});

const onFinish = (values: typeof formState) => {
  state.loginBtn = true;
  const loginParams = {
    email: values.email,
    code: values.captcha,
  };
  login(loginParams)
    .then(res => {
      loginSuccess(res);
      state.loginBtn = false;
    })
    .catch((err: any) => {
      console.log('🚀 ~ onFinish ~ err:', err);
      isLoginError.value = true;
      state.loginBtn = false;
    });
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const startTimer = () => {
  state.time = state.time - 1;
  if (state.time > 0) {
    setTimeout(startTimer, 1000);
  } else {
    state.captchaBtnDisabled = false;
    state.time = 60;
  }
};

const getCaptcha = () => {
  getEmailCaptcha(formState.email).then(() => {
    state.captchaBtnDisabled = true;
    state.time = 60;
    startTimer();
  });
};

const loginSuccess = async (res: any) => {
  const loginName = res.data.user_name || res.data.email;
  userStore.setRole(res.data.role);
  userStore.setToken(res.data.token);
  userStore.setLoginName(loginName);
  isLoginError.value = false;
  await userStore.setPrivilege(res.data.privilege);
  const redirect = typeof route.query.redirect === 'string' && route.query.redirect;
  await router.push({ path: redirect ? decodeURIComponent(redirect) : '/' });

  notification.success({
    message: '欢迎',
    description: `${loginName}，欢迎回来`,
  });
};
</script>

<style lang="less" scoped>
.user-layout-wrapper {
  height: 100%;

  &.email {
    .container {
      .main {
        max-width: 368px;
        width: 98%;
      }
    }
  }

  .container {
    width: 100%;
    min-height: 100%;
    // background: #f0f2f5 url(~@/assets/background.svg) no-repeat 50%;
    background-size: 100%;
    //padding: 50px 0 84px;
    position: relative;

    .user-layout-content {
      padding: 10% 0 24px;

      .top {
        text-align: center;

        .header {
          height: 44px;
          line-height: 44px;

          .badge {
            position: absolute;
            display: inline-block;
            line-height: 1;
            vertical-align: middle;
            margin-left: -12px;
            margin-top: -10px;
            opacity: 0.8;
          }

          .logo {
            height: 44px;
            vertical-align: top;
            margin-right: 16px;
            border-style: none;
          }

          .title {
            font-size: 33px;
            color: rgba(0, 0, 0, 0.85);
            font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
            font-weight: 600;
            position: relative;
            top: 2px;
          }
        }
        .desc {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
          margin-top: 12px;
          margin-bottom: 40px;
        }
      }

      .main {
        min-width: 260px;
        width: 368px;
        margin: 0 auto;
      }

      .footer {
        // position: absolute;
        width: 100%;
        bottom: 0;
        padding: 0 16px;
        margin: 48px 0 24px;
        text-align: center;

        .links {
          margin-bottom: 8px;
          font-size: 14px;
          a {
            color: rgba(0, 0, 0, 0.45);
            transition: all 0.3s;
            &:not(:last-child) {
              margin-right: 40px;
            }
          }
        }
        .copyright {
          color: rgba(0, 0, 0, 0.45);
          font-size: 14px;
        }
      }
    }

    a {
      text-decoration: none;
    }
  }
}
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
